#include "ordersmanagement.h"
#include "ui_ordersmanagement.h"

ordersManagement::ordersManagement(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ordersManagement)
{
    ui->setupUi(this);

    db = QSqlDatabase::database("conn");//链接数据库
    QSqlQuery query;//创建对象时，系统会自动完成跟数据库的关联
    query.setForwardOnly(true);
    ui->saveBtn->setShortcut(Qt::Key_Return);//设置保存快捷键为键盘的“回车”键

//    dishesList = new QListWidget(this);
//    dishesList->setGeometry(340,51,331,551);
//    dishesList->close();
//    dishesTitle = new QLabel(this);
//    dishesTitle->setText("订单菜品详情：");
//    dishesTitle->setGeometry(340,20,331,31);
//    dishesTitle->setAutoFillBackground(true);
//    dishesTitle->close();
    ui->stateEdit->addItem("已完成");
    ui->stateEdit->addItem("未交易");
    ui->stateEdit->setCurrentIndex(-1);
    ui->dateEdit->setDateTime(QDateTime::currentDateTime());
    ui->dateEdit->setReadOnly(true);

    //访问数据库的操作主要包括创建表，向数据库表中插入数据，删除数据，更新数据，查询数据
    //对于数据库中的表，通常只需要创建一次，而其他的操作是可以重复的

    QString sqlCreate = QString("create table if not exists orders(id integer primary key autoincrement,"
                                "date varchar(20),"
                                "address varchar(40),"
                                "customer varchar(20),"
                                "phone varchar(20),"
                                "state varchar(5),"
                                "content varchar(100));");//创建表单
    if(!query.exec(sqlCreate)){
        qDebug() << "create list error" << db.lastError();
    }
    initList();//初始化表单
}

ordersManagement::~ordersManagement()
{
    delete ui;
}

void ordersManagement::on_ordersList_itemClicked(QListWidgetItem *item)
{
    ordersForm* orders =dynamic_cast<ordersForm*>(ui->ordersList->itemWidget(item));//获取列表元素对应的的ordersForm
    int id = orders->getName();//获取对应订单id
    ui->dishesList->clear();
    QString content;

    QSqlQuery query;//创建对象时，系统会自动完成跟数据库的关联
    query.setForwardOnly(true);//减少内存浪费
    QString sqlSelect = QString ("select * from orders where id = %1;").arg(id);

    if(!query.exec(sqlSelect)){//查找关键字
        qDebug() << "search data error" << db.lastError();
        return;
    }else {
        if(query.next()){
            ui->idEdit->setText(query.value("id").toString());
            QDateTime dateTime = QDateTime::fromString(query.value("date").toString(),"yyyy/MM/dd hh:mm");
            ui->dateEdit->setDateTime(dateTime);
            ui->addressEdit->setText(query.value("address").toString());
            if(query.value("address").toString().startsWith("T")){
                ui->changingLb->setText("桌号：");
            }else{
                ui->changingLb->setText("地址：");
            }
            ui->customerEdit->setText(query.value("customer").toString());
            ui->phoneEdit->setText(query.value("phone").toString());
            ui->stateEdit->setCurrentText(query.value("state").toString());
            content = query.value("content").toString();
            QStringList list = content.split(" ",QString::SkipEmptyParts);//将订单中的菜品分别列出
            editTrue();//显示信息到编辑框，等待编辑

            for(int i = 0; i< list.size();i++)//查找订单包含的所有菜品信息并且显示
            {
                QString name = list.at(i);
                QString sqlSelect = QString ("select * from menu where name = '%1';").arg(name);
                if(!query.exec(sqlSelect)){//遍历menu表单
                    qDebug() << "insert data error" << db.lastError();
                }else {
                    while(query.next()){//读取数据库，填写表单
                        QString iniName = query.value("name").toString();
                        QString iniIngredients = query.value("ingredients").toString();
                        int iniPrize = query.value("prize").toInt();
                        int iniNumber = query.value("number").toInt();
                        itemForm* dishesItem = new itemForm;
                        dishesItem->setDishes(iniName,iniIngredients,iniPrize,iniNumber);
                        QListWidgetItem* item = new QListWidgetItem;
                        item->setSizeHint(QSize(700,70));

                        ui->dishesList->addItem(item);
                        ui->dishesList->setItemWidget(item,dishesItem);
                    }
                }
            }
        }
    }
}

void ordersManagement::on_searchBtn_clicked()
{
    clearEdit();//清除编辑栏内容
    editFalse();
    QString keyword = QInputDialog::getText(this, "查询", "请输菜品id：");//获取菜品id
    if(!keyword.isEmpty()){

        QSqlQuery query;//创建对象时，系统会自动完成跟数据库的关联
        query.setForwardOnly(true);//减少内存浪费
        QString sqlSelect = QString ("select * from orders where id = %1;").arg(keyword);

        if(!query.exec(sqlSelect)){//查找关键字
            qDebug() << "search data error" << db.lastError();
            return;
        }else {
            if(query.next()){
                ui->idEdit->setText(query.value("id").toString());
                QDateTime dateTime = QDateTime::fromString(query.value("date").toString(),"yyyy/MM/dd hh:mm");
                ui->dateEdit->setDateTime(dateTime);
                ui->addressEdit->setText(query.value("address").toString());
                if(query.value("address").toString().startsWith("T")){
                    ui->changingLb->setText("桌号：");
                }else{
                    ui->changingLb->setText("地址：");
                }
                ui->customerEdit->setText(query.value("customer").toString());
                ui->phoneEdit->setText(query.value("phone").toString());
                ui->stateEdit->setCurrentText(query.value("state").toString());
                QString content = query.value("content").toString();
                QStringList list = content.split(" ",QString::SkipEmptyParts);//将订单中的菜品分别列出
                //qDebug() << list;

                editTrue();//显示信息到编辑框，等待编辑
                //显示结果到编辑框，等待编辑
                editTrue();//查找到菜品，进行编辑操作
                ui->dishesList->clear();

                for(int i = 0; i< list.size();++i)//查找订单包含的所有菜品信息并且显示
                {
                    QString name = list.at(i);
                    //qDebug() << name;
                    QString sqlSelect = QString ("select * from menu where name = '%1';").arg(name);
                    if(!query.exec(sqlSelect)){//遍历menu表单
                        qDebug() << "insert data error" << db.lastError();
                    }else {
                        while(query.next()){//读取数据库，填写表单
                            QString iniName = query.value("name").toString();
                            QString iniIngredients = query.value("ingredients").toString();
                            int iniPrize = query.value("prize").toInt();
                            int iniNumber = query.value("number").toInt();
                            itemForm* dishesItem = new itemForm;
                            dishesItem->setDishes(iniName,iniIngredients,iniPrize,iniNumber);
                            QListWidgetItem* item = new QListWidgetItem;

                            item->setSizeHint(QSize(700,70));

                            ui->dishesList->addItem(item);
                            ui->dishesList->setItemWidget(item,dishesItem);
                        }
                    }
                }
            }else{
                QMessageBox::information(this,"友情提示","没有相应订单，请确认号码输入是否正确");
            }
        }
    }else{
        QMessageBox::information(this,"友情提示","请输入号码");
    }
}

void ordersManagement::on_saveBtn_clicked()
{
    QSqlQuery query;//创建对象时，系统会自动完成跟数据库的关联
    query.setForwardOnly(true);

    int id = ui->idEdit->text().toInt();
    QString date = ui->dateEdit->dateTime().toString("yyyy/MM/dd hh:mm");
    QString address = ui->addressEdit->text();
    QString customer = ui->customerEdit->text();
    QString phone = ui->phoneEdit->text();
    QString state = ui->stateEdit->currentText();
    //获取信息
    if(date.isEmpty()||address.isEmpty()||customer.isEmpty()||phone.isEmpty()||state.isEmpty()){
        QMessageBox::information(this, "友情提示", "订单信息不完整，请完善");
        return;
    }

    QString sqlUpdate = QString("update orders set date = '%1',"
                                "address = '%2',"
                                "customer = '%3',"
                                "phone = '%4',"
                                "state = '%5' "
                                "where id = %6").arg(date).arg(address)
            .arg(customer).arg(phone).arg(state).arg(id);

    //    UPDATE table_name
    //    SET column1 = value1, column2 = value2...., columnN = valueN
    //    WHERE [condition];
    if(!query.exec(sqlUpdate)){
        qDebug() << "update data error" << db.lastError();
    }else{
        QMessageBox::information(this, "友情提示", "修改订单成功");
    }
    initList();//刷新订单表格
    clearEdit();//清空编辑框
    editFalse();//禁止编辑
}

void ordersManagement::on_deleteBtn_clicked()
{
    int id = ui->idEdit->text().toInt();
    QString sqlDelete = QString("delete from orders where id = %1").arg(id);
    QSqlQuery query;//创建对象时，系统会自动完成跟数据库的关联

    if(!query.exec(sqlDelete)){
        qDebug() << "delete data error" << db.lastError();
    }else{
        QMessageBox::information(this, "友情提示", "删除订单成功");
    }//删除菜品操作

    clearEdit();//清空编辑栏数据
    editFalse();//不可编辑状态
    initList();//刷新表
}

void ordersManagement::initList()
{
    ui->ordersList->clear();//清空表格


    QSqlQuery query;//创建对象时，系统会自动完成跟数据库的关联
    query.setForwardOnly(true);

    QString sqlSelect = QString ("select * from orders order by id desc;");
    if(!query.exec(sqlSelect)){//遍历表单
        qDebug() << "select data error" << db.lastError();
    }else {
        while(query.next()){//读取数据库，填写表单
            int id = query.value("id").toInt();
            QString date = query.value("date").toString();
            QString address = query.value("address").toString();
            QString customer = query.value("customer").toString();
            QString phone = query.value("phone").toString();
            QString state = query.value("state").toString();
            QString content = query.value("content").toString();
            ordersForm* ordersItem = new ordersForm;
            ordersItem->setOrders(id,date,address,customer,phone,state);
            QListWidgetItem* item = new QListWidgetItem;

            item->setSizeHint(QSize(1420,70));
            ui->ordersList->addItem(item);
            ui->ordersList->setItemWidget(item,ordersItem);
        }
    }
}

void ordersManagement::clearEdit()//清空编辑框
{
    ui->idEdit->clear();
    ui->dateEdit->setDateTime(QDateTime::currentDateTime());
    ui->addressEdit->clear();
    ui->customerEdit->clear();
    ui->phoneEdit->clear();
    ui->stateEdit->setCurrentIndex(-1);
}

void ordersManagement::editTrue()//可编辑
{
    ui->dateEdit->setReadOnly(false);
    ui->addressEdit->setReadOnly(false);
    ui->customerEdit->setReadOnly(false);
    ui->phoneEdit->setReadOnly(false);
}

void ordersManagement::editFalse()//不可编辑
{
    ui->idEdit->setReadOnly(true);
    ui->dateEdit->setReadOnly(true);
    ui->addressEdit->setReadOnly(true);
    ui->customerEdit->setReadOnly(true);
    ui->phoneEdit->setReadOnly(true);
}
